import { useEffect } from "react";
import { useCallbackRef } from "./useCallbackRef";

/**
 * 定时器
 */
export default function useInterval(callback: () => void, delay?: number) {
  const fnRef = useCallbackRef(callback);

  useEffect(() => {
    // 如果 delay 为 null 或 undefined，则不设置计时器
    if (delay === null || delay === undefined) return;

    // 每次 interval 触发时调用最新的回调函数
    const tick = () => {
      fnRef();
    };
    // 设置计时器
    const id = setInterval(tick, delay);
    // 清除计时器
    return () => clearInterval(id);
  }, [delay]);
}
